package com.Sdebruijn.curriculumvitae.sync.remote;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * Client for RESTFul systems.
 */
public class RestClient {

	/**
	 * Type of the Request.
	 */
	public enum RequestMethod {
		/** The GET. */
		GET,
		/** The POST. */
		POST,
		/** The PUT. */
		PUT,
		/** The DEL. */
		DEL
	}

	/** The params. */
	private ArrayList<NameValuePair> params;

	/** The headers. */
	private ArrayList<NameValuePair> headers;

	/** The remote url. */
	private String remoteUrl;

	/** The response code. */
	private int responseCode;

	/** The message. */
	private String errorMessage;

	/** The response. */
	private String response;

	/** The response stream. */
	private InputStream responseStream;

	/** The need stream instead of string. */
	private boolean needStreamInsteadOfString = false;

	/**
	 * Gets the response.
	 * 
	 * @return the response
	 */
	public String getResponse() {
		return response;
	}

	/**
	 * Gets the response stream.
	 * 
	 * @return the response stream
	 */
	public InputStream getResponseStream() {
		return responseStream;
	}

	/**
	 * Gets the error message.
	 * 
	 * @return the error message
	 */
	public String getErrorMessage() {
		return errorMessage;
	}

	/**
	 * Gets the response code.
	 * 
	 * @return the response code
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * Instantiates a new rest client.
	 * 
	 * @param url
	 *            the url
	 */
	public RestClient(final String url) {
		this.remoteUrl = url;
		this.params = new ArrayList<NameValuePair>();
		this.headers = new ArrayList<NameValuePair>();
	}

	/**
	 * Clear params.
	 */
	public void clearParams() {
		params.clear();
	}

	/**
	 * Clear headers.
	 */
	public void clearHeaders() {
		headers.clear();
	}

	/**
	 * Add parameter to request.
	 * 
	 * @param name
	 *            Name of the parameter
	 * @param value
	 *            Value of the parameter
	 */
	public void addParam(final String name, final String value) {
		params.add(new BasicNameValuePair(name, value));
	}

	/**
	 * Add header parameter to request.
	 * 
	 * @param name
	 *            Name of the parameter
	 * @param value
	 *            Value of the parameter
	 */
	public void addHeader(final String name, final String value) {
		headers.add(new BasicNameValuePair(name, value));
	}

	/**
	 * Execute a RestFul call.
	 * 
	 * @param method
	 *            {@link RequestMethod} Can be either GET or POST
	 * @throws IllegalArgumentException
	 *             the illegal argument exception
	 * @throws UnsupportedEncodingException
	 *             the unsupported encoding exception
	 */
	public void execute(final RequestMethod method)
			throws IllegalArgumentException, UnsupportedEncodingException {
		switch (method) {
		case GET:
			// add parameters
			String combinedParams = "";
			if (!params.isEmpty()) {
				combinedParams += "?";
				for (NameValuePair p : params) {
					String paramString = p.getName() + "="
							+ URLEncoder.encode(p.getValue(), "UTF-8");

					if (combinedParams.length() > 1) {
						combinedParams += "&" + paramString;
					} else {
						combinedParams += paramString;
					}
				}
			}
			HttpGet getRequest = new HttpGet(remoteUrl + combinedParams);
			// add headers
			for (NameValuePair h : headers) {
				getRequest.addHeader(h.getName(), h.getValue());
			}
			executeRequest(getRequest, remoteUrl);
			break;
		case POST:
			HttpPost postRequest = new HttpPost(remoteUrl);
			// add headers
			for (NameValuePair h : headers) {
				postRequest.addHeader(h.getName(), h.getValue());
			}
			if (!params.isEmpty()) {
				postRequest.setEntity(new UrlEncodedFormEntity(
						(List<? extends NameValuePair>) params, HTTP.UTF_8));
			}
			executeRequest(postRequest, remoteUrl);
			break;
		default:
			break;
		}
	}

	/**
	 * Execute post request.
	 * 
	 * @param message
	 *            the message
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public void executePostRequest(final String message) throws IOException {
		URL url = new URL(remoteUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setInstanceFollowRedirects(false);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("charset", "utf-8");
		connection.setRequestProperty("Content-Length",
				"" + Integer.toString(message.getBytes().length));
		connection.setUseCaches(false);

		DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
		wr.writeBytes(message);
		wr.flush();
		wr.close();

		// Get the response

		responseCode = connection.getResponseCode();

		if (connection.getErrorStream() != null) {
			errorMessage = convertStreamToString(connection.getErrorStream());
		}

		if (connection.getInputStream() != null) {
			response = convertStreamToString(connection.getInputStream());
		}

		connection.disconnect();
	}

	/**
	 * Execute post request.
	 * 
	 * @param message
	 *            the message
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public void executePutRequest(final String message) throws IOException {
		URL url = new URL(remoteUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setInstanceFollowRedirects(false);
		connection.setRequestMethod("PUT");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("charset", "utf-8");
		connection.setRequestProperty("Content-Length",
				"" + Integer.toString(message.getBytes().length));
		connection.setUseCaches(false);

		DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
		wr.writeBytes(message);
		wr.flush();
		wr.close();

		// Get the response

		responseCode = connection.getResponseCode();

		if (connection.getErrorStream() != null) {
			errorMessage = convertStreamToString(connection.getErrorStream());
		}

		if (connection.getInputStream() != null) {
			response = convertStreamToString(connection.getInputStream());
		}

		connection.disconnect();
	}

	/**
	 * Execute post request.
	 * 
	 * @param message
	 *            the message
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public void executeDelRequest(final String message) throws IOException {
		URL url = new URL(remoteUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setInstanceFollowRedirects(false);
		connection.setRequestMethod("DEL");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("charset", "utf-8");
		connection.setRequestProperty("Content-Length",
				"" + Integer.toString(message.getBytes().length));
		connection.setUseCaches(false);

		DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
		wr.writeBytes(message);
		wr.flush();
		wr.close();

		// Get the response

		responseCode = connection.getResponseCode();

		if (connection.getErrorStream() != null) {
			errorMessage = convertStreamToString(connection.getErrorStream());
		}

		if (connection.getInputStream() != null) {
			response = convertStreamToString(connection.getInputStream());
		}

		connection.disconnect();
	}

	/**
	 * Execute request.
	 * 
	 * @param request
	 *            the request
	 * @param url
	 *            the url
	 */
	private void executeRequest(final HttpUriRequest request, final String url) {
		HttpClient client = new DefaultHttpClient();

		HttpResponse httpResponse;

		try {
			httpResponse = client.execute(request);
			responseCode = httpResponse.getStatusLine().getStatusCode();
			errorMessage = httpResponse.getStatusLine().getReasonPhrase();

			HttpEntity entity = httpResponse.getEntity();

			if (entity != null) {

				responseStream = entity.getContent();

				if (!needStreamInsteadOfString) {
					response = convertStreamToString(responseStream);

					// Closing the input stream will trigger connection release
					responseStream.close();
				}
			}

		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		} catch (IOException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		}
	}

	/**
	 * Convert stream to string.
	 * 
	 * @param is
	 *            the is
	 * @return the string
	 */
	private static String convertStreamToString(final InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * @param needStreamInsteadOfString
	 *            the needStreamInsteadOfString to set
	 */
	public void setNeedStreamInsteadOfString(boolean needStreamInsteadOfString) {
		this.needStreamInsteadOfString = needStreamInsteadOfString;
	}
}
